//Show lines in the region lineno-spread, lineo+spread.
//
//EXAMPLE
//
//     $ compiler bad.file
//     Error on line 450
//     $ <bad.file near -r1
//     The real error
//     Where it was reported
//     This line intentionally left vague
//
package main

import (
	"flag"
	"strconv"
	"os"
	"fmt"
	"bufio"
)

var spread = flag.Int("r", 5, "how many lines to display before and after")

var star = map[bool]string{true: "* ", false: "  "}

func Usage(msg string) {
	fmt.Fprintln(os.Stderr, msg+"\n")
	flag.Usage()
	os.Exit(1)
}

//Usage: %name %flags lineno
func main() {
	flag.Parse()
	if flag.NArg() != 1 {
		Usage("No line number specified.")
	}

	line, err := strconv.Atoi(flag.Arg(0))
	if err != nil || line < 0 {
		Usage("Invalid line number specified.")
	}
	if *spread < 0 {
		Usage("Invalid number of lines to display before and after specified.")
	}

	var first, last int
	if f := line - *spread; f >= 0 {
		first = f
	}
	last = line + *spread + 1

	sin := bufio.NewReader(os.Stdin)
	for lno := 0; lno < last; lno++ {
		in, err := sin.ReadString('\n')
		if err != nil {
			return
		}

		if lno >= first && lno <= last {
			fmt.Print(star[lno == line], in)
		}
	}
}
